package org.micode.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class UrlUtils {

    //用于获取url参数
    public static Map<String, String> getQueryMap(String queryStr) {
        Map<String, String> queryMap = new HashMap<>();
        if (!StringUtils.isEmpty(queryStr)) {
            String[] queryParam = queryStr.split("&");
            Arrays.stream(queryParam).forEach(s -> {
                String[] kv = s.split("=", 2);
                String value = kv.length == 2 ? kv[1] : "";
                queryMap.put(kv[0], value);
            });
        }
        return queryMap;
    }

    /**
     * 读取相对路径
     * 例如:
     * fullUrl: http://192.168.100.245/document/type/旅行社.png
     * 返回: /document/type/旅行社.png
     *
     * @param fullUrl
     * @return
     */
    public static String readRelativeUrl(String fullUrl) {
        if (StringExtUtils.isAnyEmpty(fullUrl)) {
            return fullUrl;
        }
        String url = fullUrl.replaceFirst("http://", "")
                .replaceFirst("https://", "");
        if (url.charAt(0) != '/') {
            url = "/" + url;
        } else {
            int pos = url.indexOf("/");
            url = url.substring(pos);
        }
        return url;
    }

    /**
     * 读取域名路径
     * 例如:
     * fullUrl: http://192.168.100.245/document/type/旅行社.png
     * 返回: http://192.168.100.245
     *
     * @param fullUrl
     * @return
     */
    public static String readDomainUrl(String fullUrl) {
        if (StringExtUtils.isAnyEmpty(fullUrl)) {
            return fullUrl;
        }
        String url = fullUrl.replaceFirst("http://", "       ")
                .replaceFirst("https://", "        ");
        int pos = url.indexOf("/");
        if (pos <= 0) {
            url = fullUrl;
        } else {
            url = fullUrl.substring(0, pos);
        }
        return url;
    }

    /**
     * 读取域名路径
     * 例如:
     * fullUrl: http://192.168.100.245/document/type/旅行社.png
     * 返回: http://192.168.100.245
     *
     * @param domainUrl
     * @param relativeUrl
     * @return
     */
    public static String concatUrl(String domainUrl, String relativeUrl) {
        String realDomain = readDomainUrl(domainUrl);
        String realRelative = readRelativeUrl(relativeUrl);

        if (StringExtUtils.isAnyEmpty(realDomain) ||
                StringExtUtils.isAnyEmpty(realRelative)) {
            return "";
        }
        return realDomain + realRelative;
    }

    public static void main(String[] args) {
        System.out.println(concatUrl(
                "http://192.168.100.245/",
                "document/type/heheh.png"
                ));
    }

}
